<?php

namespace app\admin\controller\business;

use app\common\controller\Backend;
use app\common\model\Business\Business;
use app\common\model\Business\Receive;
use app\common\model\Business\Source;
use app\common\model\Region;
use Exception;
use fast\Http;
use fast\Random;
use think\Db;
use think\exception\ValidateException;
use think\exception\PDOException;

/**
 * 客户管理
 *
 * @icon fa fa-circle-o
 */
class Privatesea extends Backend
{

    /**
     * Privatesea模型对象
     * @var \app\admin\model\business\Privatesea
     */
    protected $model = null;
    protected $receiveModel = null;
    protected $sourceModel = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new Business();
        $this->sourceModel = new Source();
        $this->receiveModel = new Receive();
        $this->view->assign("genderList", $this->model->getGenderList());
        $this->view->assign("dealList", $this->model->getDealList());
        $this->view->assign("authList", $this->model->getAuthList());

        $this->assignconfig("sourceList", $this->model->getSourceList());
        $this->modelValidate = true;
        $this->request->filter('trim,strip_tags,htmlspecialchars');
        $this->relationSearch = true;
        $this->dataLimit = 'auth';
        $this->dataLimitField = 'adminid';
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

     public function index()
     {
         //设置过滤方法
         $this->request->filter(['strip_tags', 'trim']);
         if (false === $this->request->isAjax()) {
             return $this->view->fetch();
         }
         //如果发送的来源是 Selectpage，则转发到 Selectpage
         if ($this->request->request('keyField')) {
             return $this->selectpage();
         }
 
         $filter = json_decode($this->request->get('filter'),true);
         $op = json_decode($this->request->get('op'),true);
         if (isset($filter['source.name'])){
             $cost_where['source.name'] = $filter['source.name'];
             $filter['source.id'] = $filter['source.name'];
             $op['source.id'] = $op['source.name'];
             unset($filter['source.name']);
             unset($op['source.name']);
         }
         $this->request->get(['filter'=>json_encode($filter)]);
         $this->request->get(['op'=>json_encode($op)]);
 
         [$where, $sort, $order, $offset, $limit] = $this->buildparams();
         // halt($where);
         $wherePrivatesea = ['adminid'=>$this->auth->id];
         $list = $this->model
             ->with(['source'])
             ->where($where)
             ->where($wherePrivatesea)
             ->order($sort, $order)
             ->paginate($limit);
         $result = ['total' => $list->total(), 'rows' => $list->items()];
         return json($result);
     }

     public function add()
    {
        if (false === $this->request->isPost()) {
            $sourceList = build_select('row[sourceid]',$this->sourceModel->column('id,name'),[],['class'=>'selectpicker', 'required'=>'']);
            $this->assign('sourceList',$sourceList);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = array_filter($params);
        $params = $this->preExcludeFields($params);
        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        if($this->model->where(['mobile'=>$params['mobile']])->find())
        {
            $this->error(__('%s already exists',__('Mobile')));
        }
        if(isset($params['email'])&&$this->model->where(['email'=>$params['email']])->find())
        {
            $this->error(__('%s already exists',__('Email')));
        }
        $result = false;
        Db::startTrans();
        try {
            $params['adminid'] = $this->auth->id;
            if(isset($params['code'])&&$params['code'])
            {
                $code = explode(',',$params['code']);
                $params['province'] = $code[0]=='undefined'?'':$code[0];
                $params['city'] = $code[1]=='undefined'?'':$code[1];
                $params['district'] = $code[2]=='undefined'?'':$code[2];
            }
            unset($params['code']);
            $params['salt'] = Random::alnum(10);
            // halt($params);
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                // $this->model->validateFailException()->validate($validate);
                $this->validateFailException()->validate($params,$validate);
            }
            $params['password'] = md5(md5($params['password']) . $params['salt']);
            $this->model->allowField(true)->save($params);

            $adminid = $this->auth->id;
            $dataReceive = [
                'applyid'=>$adminid,
                'status'=>'apply',
                'busid'=>$this->model->id,
            ];
            $result = $this->receiveModel->save($dataReceive);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }
    private function randNickname($gender) 
    {
        // 接口URL
        $url = 'http://hn.api.yesapi.net/';
        $nickname = '';
        // 发送GET请求
        $resparams = [
            's'=>'App.Common_Nickname.RandOne',
            'return_data'=>'0',
            'app_key'=>'6791A8239442AABF833ED28A60DBD8DF',
            'sign'=>'9877A994EDDB7B658C848CC29D96006E',
            'need_lan'=>'中文',
        ];
        $genderList = ['保密','男','女'];
        if($gender){
            $resparams['need_sex'] = $genderList[$gender];
        }
        $response = Http::get($url,$resparams);
        
        // 处理响应
        $response = json_decode($response, true);
        if($response['ret']==200){
            $nickname = $response['data']['nickname'];
        }
        return $nickname;
    }
    private function randAddress()
    {
        $region = ['province'=>'','city'=>'','district'=>''];
        $layerName = ['province','city','district'];
        $r = Region::count('code');
        $randregion = rand(0,$r-1);
        $randparentpath = Region::field('parentpath')->limit($randregion,1)->select()->toArray()[0]['parentpath'];
        $list = explode(',',$randparentpath);
        foreach(range(0,count($list)-1) as $layer){
            $region[$layerName[$layer]] = $list[$layer];
        }
        return $region;
    }
    private function randAvatar($type,$params=[])
    {
        $avatarPath = '/' . 'uploads' . '/' . date('Ymd',time());
        $avatar = $avatarPath . '/' . Random::alnum(32) . '.jpg';
        $avatarPath = ROOT_PATH . 'public' . $avatarPath;
        $avatarFile =  ROOT_PATH . 'public' . $avatar;
        if (!file_exists($avatarPath)) {
            mkdir($avatarPath, 0777, true);
        }
        if($type=='xjh')
        {
            $randImageUrl = 'https://img.xjh.me/random_img.php?return=json';
            $response = Http::get($randImageUrl);
            $response = json_decode($response, true);
            $imageUrl = 'https:'.$response['img'];

            $imageData = Http::get($imageUrl);
            file_put_contents($avatarFile, $imageData);
        }else if($type=='qq')
        {
            $qq = $params['qq'];
            $imageUrl = 'http://q1.qlogo.cn/g?b=qq&nk='.$qq.'&s=640';
            // 初始化cURL会话
            $ch = curl_init();
            
            // 设置cURL选项
            curl_setopt($ch, CURLOPT_URL, $imageUrl);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            
            // 执行cURL会话
            $imageData = curl_exec($ch);
            // 关闭cURL会话
            curl_close($ch);
            // 指定本地文件路径
            
            // 将图片数据写入到本地文件
            file_put_contents($avatarFile, $imageData);
        }
        return $avatar;
    }
    private function randBusiness()
    {
        $params = [];
        //随机手机号
        $mobile = "1";
        $mobile .= random_int(3,9);
        for($n=0;$n<9;$n++){
            $mobile .= random_int(0,9);
        }
        $params['mobile'] = $mobile;
        //随机性别
        $params['gender'] = random_int(0,2);
        //随机昵称
        $params['nickname'] = $this->randNickname($params['gender']);
        //随机密码盐
        $params['salt'] = Random::alnum(10);
        //随机来源
        $sourceidAll = [];
        foreach($this->model->getSourceList() as $source)
        {
            $sourceidAll[] = $source['id'];
        }
        $params['sourceid'] = $sourceidAll[array_rand($sourceidAll)];
        //随机地址
        $region = $this->randAddress();
        $params['province'] = $region['province'];
        $params['city'] = $region['city'];
        $params['district'] = $region['district'];
        //随机金额
        $params['money'] = random_int(0,1000000)/100;
        //随机邮箱
        $qq = "";
        for($n=0;$n<9;$n++){
            $qq = random_int(0,9).$qq;
        }
        $qq = random_int(1,3).$qq;
        $params['email'] = $qq.'@qq.com';
        //随机头像
        // $avatar = $this->randAvatar('qq',['qq'=>$qq]);
        $avatar = $this->randAvatar('xjh');
        $params['avatar'] = $avatar;
        //固定参数:密码
        $params['password'] = '123456';
        $params['deal'] = 0;
        $params['auth'] = 0;
        $params['adminid'] = $this->auth->id;
        return $params;
    }
    public function randadd()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $validate = [
            [
                'addnumber'=>['require','integer','>:0','<=:10']
            ],
            [
                'addnumber.require'=>'数量不能为空',
                'addnumber.integer'=>'数量需为整数',
                'addnumber.>:0'=>'数量需大于零',
                'addnumber.<=:0'=>'数量不能超过十个',
            ]
        ];
        $result = false;
        Db::startTrans();
        try {
            $this->validateFailException()->validate($params,...$validate);
            $paramsList = [];
            foreach(range(1,$params['addnumber']) as $number)
            {
                $params = $this->randBusiness();
                //是否采用模型验证
                if ($this->modelValidate) {
                    $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                    // $this->model->validateFailException()->validate($validate);
                    $this->validateFailException()->validate($params,$validate);
                }
                $params['password'] = md5(md5($params['password']) . $params['salt']);
                $paramsList[] = $params;
            }
            // halt($paramsList);
            $result = $this->model->allowField(true)->saveAll($paramsList);
            $dataReceive = [];
            $adminid = $this->auth->id;
            if($result!==false){
                foreach ($result as $item){
                    // 打印每条数据的ID
                    $busid = $item['id'];
                    $dataReceive[] = [
                        'applyid'=>$adminid,
                        'status'=>'apply',
                        'busid'=>$busid,
                    ];
                }
            }
            $result = $this->receiveModel->saveAll($dataReceive);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            $sourceList = build_select('row[sourceid]',$this->sourceModel->column('id,name'),[$row['sourceid']],['class'=>'selectpicker', 'required'=>'']);
            $this->assign('sourceList',$sourceList);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = array_filter($params);
        if($this->model->where(['id'=>['<>',$ids],'mobile'=>$params['mobile']])->find())
        {
            $this->error(__('%s already exists',__('Mobile')));
        }
        if(!isset($params['email'])){

        }else if(isset($params['email'])&&$this->model->where(['id'=>['<>',$ids],'email'=>$params['email']])->find())
        {
            $this->error(__('%s already exists',__('Email')));
        }else if(isset($params['email'])&&$row['email']==$params['email']){
            unset($params['email']);
        }else{
            $params['auth'] = 0;
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            if(isset($params['code'])&&$params['code'])
            {
                $code = explode(',',$params['code']);
                $params['province'] = $code[0]=='undefined'?'':$code[0];
                $params['city'] = $code[1]=='undefined'?'':$code[1];
                $params['district'] = $code[2]=='undefined'?'':$code[2];
            }
            unset($params['code']);
            $ispassword = isset($params['password'])&&$params['password'];
            if(!$ispassword){
                $params['password'] = '123456';
            }
            if(isset($params['avatar'])&&$params['avatar']!=$row['avatar']){
                $avatarPath = ROOT_PATH . 'public' . $row['avatar'];
                if(is_file($avatarPath)){
                    unlink($avatarPath);
                }
            }
            // halt($params);
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                // $row->validateFailException()->validate($validate);
                $this->validateFailException()->validate($params,$validate);
            }
            if($ispassword){
                $params['salt'] = Random::alnum(10);
                $params['password'] = md5(md5($params['password']) . $params['salt']);
            }else{
                unset($params['password']);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }
    public function recovery($ids = null)
    {
        $rows = $this->model->where('id','in',$ids)->select();
        if (!$rows->count()) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($rows->get(0)[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        $adminid = $this->auth->id;
        $dataBusiness = [];
        $dataReceive = [];
        foreach($rows as $row)
        {
            $dataBusiness[] = [
                'id'=>$row['id'],
                'adminid'=>null,
            ];
            $dataReceive[] = [
                'applyid'=>$adminid,
                'status'=>'recovery',
                'busid'=>$row['id']
            ];
        }
        
        $result = false;
        Db::startTrans();
        try {
            $this->model->isUpdate(true)->saveAll($dataBusiness);
            $result = $this->receiveModel->saveAll($dataReceive);
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }
    public function destroy($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post('ids');
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        if ($ids) {
            $this->model->where($pk, 'in', $ids);
        }
        $count = 0;
        Db::startTrans();
        try {
            $list = $this->model->onlyTrashed()->select();
            $avatarList = [];
            foreach ($list as $item) {
                $avatarList[] = ROOT_PATH . 'public' . $item['avatar'];
                $count += $item->delete(true);
            }
            foreach($avatarList as $avatarFile)
            {
                if(is_file($avatarFile))
                {
                    unlink($avatarFile);
                }
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }
}